package fr.upmc.cie;

import java.util.ArrayList;
import java.util.Collections;

import fr.upmc.cie.data.CategorieItem;
import fr.upmc.cie.data.ChannelItem;
import fr.upmc.cie.data.DataManager;
import fr.upmc.cie.data.TicketItem;
import fr.upmc.cie.ext.TicketListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ListTickets extends Activity{
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_tickets);
		
		final ListView lv = (ListView) this.findViewById(R.id.listTickets);
		
		final ArrayList<TicketItem> tickets;
		
		/*
		 * Obtenir le type de source (categorie=1 ou channel=2)
		 */
		if (this.getIntent().getExtras().getInt("type")==1){
			//Charger les tickets disponibles
			long id = this.getIntent().getExtras().getInt("categorie");
			CategorieItem ci = DataManager.getCategorieManager(this).getCategorieById(id, this);
			tickets = new ArrayList<TicketItem>();
			ArrayList<TicketItem>tempo = new ArrayList<TicketItem>();
			for (ChannelItem tmp : ci.getChannels()){
				tempo.addAll(DataManager.getTicketManager(this).getListById(tmp.getId()));
			}
			Collections.sort(tempo);
			for (int i=tempo.size()-1;i>=0;i--){
				tickets.add(tempo.get(i));
			}
			
		}else{
			//Charger les tickets disponibles
			long id = this.getIntent().getExtras().getInt("channel");
			tickets = DataManager.getTicketManager(this).getListById(id);
		}
		
		TicketListAdapter tla = new TicketListAdapter(this, tickets);
		
		lv.setAdapter(tla);
		
		lv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//Afficher le ticket dans la position donnee
				Intent i = new Intent();
				i.putExtra("ticket", tickets.get(position));
				i.setClass(view.getContext(), TicketDisplay.class);
				startActivity(i);
			}
			
		});
	}

}
